<template>
  <div class="edit-paper">
    <div class="top-buttons">
      <el-button type="primary" @click="openAddPaperDialog">+ 新增试卷</el-button>
      <el-button type="primary" @click="openImportFromBankDialog">+ 从课程题库中导入</el-button>
    </div>

    <el-select v-model="selectedViewPaper" placeholder="请选择试卷" @change="handleCurrentChange" class="full-width">
      <el-option label="所有试卷" value="all"></el-option>
      <el-option v-for="(paper, index) in papers" :key="paper.paper_id" :label="paper.paper_title" :value="index"></el-option>
    </el-select>

    <!-- 表格展示 -->
    <el-table :data="filteredTableData" style="width: 100%" class="paper-table">
      <!-- 试卷名称 -->
      <el-table-column prop="paper_title" label="试卷名称" width="180"></el-table-column>
      
      <!-- 试卷满分 -->
      <el-table-column label="满分" width="100">
        <template #default="{ row }">
          
          {{ calculateTotalScore(row.questions) }} 分
        </template>
      </el-table-column>

      <!-- 题目描述 -->
      <el-table-column label="题目描述">
        <template #default="{ row }">
          <el-collapse>
            <el-collapse-item v-for="(question, qIndex) in row.questions" :key="qIndex">
              <template #title>
                <div class="question-header">
                  <!-- 序号 -->
                  <span class="question-index">{{ qIndex + 1 }}.</span>
                  <span class="question-title">{{ question.title }}</span>
                  <span class="question-type">
                    <p v-if="question.qs_type=='only_sel'">[单选]</p>
                    <p v-if="question.qs_type=='many_sel'">[多选]</p>
                    <p v-if="question.qs_type=='yesorno'">[判断]</p>
                  </span>
                </div>
              </template>

              <div class="question-options">
                <div v-if="question.qs_type=='yesorno'">
                  <div>A: {{ question.a_option }}</div>
                  <div>B: {{ question.b_option }}</div>
                </div>
                <div v-else>
                  <div>A: {{ question.a_option }}</div>
                  <div>B: {{ question.b_option }}</div>
                  <div>C: {{ question.c_option }}</div>
                  <div>D: {{ question.d_option }}</div>
                </div>
              </div>

              <!-- 正确答案 -->
              <div class="correct-answer">
                正确答案: {{ question.right_ans }}
              </div>

              <!-- 删除题目按钮 -->
              <el-button 
                type="text" 
                size="small" 
                class="delete-question-btn" 
                @click="deleteQuestion(row, qIndex)">
                删除题目
              </el-button>
            </el-collapse-item>
          </el-collapse>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="100">
        <template #default="{ $index }">
          <el-button type="danger" size="mini" @click="deletePaper($index)">删除试卷</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="totalPapers">
      </el-pagination>
    </div>

    <!-- 新增试卷弹窗 -->
    <el-dialog title="新增试卷" v-model="newPaperDialogVisible">
      <el-form :model="newPaper">
        <el-form-item label="试卷名称" :rules="{ required: true, message: '请输入试卷名称', trigger: 'blur' }">
          <el-input v-model="newPaper.paper_title"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="newPaperDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addNewPaper">确定</el-button>
      </template>
    </el-dialog>

    <!-- 从课程题库中导入弹窗 -->
    <el-dialog title="从课程题库中导入" v-model="importDialogVisible" width="70%">
      <el-select v-model="selectedImportPaper" placeholder="请选择试卷" class="import-paper-select full-width">
        <el-option v-for="(paper, index) in papers" :key="index" :label="paper.paper_title" :value="index"></el-option>
      </el-select>
      <div class="import-top">
        <el-input
          v-model="searchQuery"
          placeholder="搜索题目"
          class="import-search"
          prefix-icon="el-icon-search"
          @input="filterQuestionBank"
        ></el-input>
      </div>
      <el-table :data="filteredQuestionBank" style="width: 100%" class="question-table">
        <el-table-column prop="title" label="题目描述" width="300"></el-table-column>
        <el-table-column label="题目类型" width="150">
          <template #default="{ row }">
            <span v-if="row.qs_type === 'only_sel'">单选</span>
            <span v-else-if="row.qs_type === 'many_sel'">多选</span>
            <span v-else-if="row.qs_type === 'yesorno'">判断</span>
            <span v-else>未知类型</span> <!-- 如果题目类型未识别 -->
          </template>
        </el-table-column>
        <el-table-column prop="a_option" label="选项A" width="100"></el-table-column>
        <el-table-column prop="b_option" label="选项B" width="100"></el-table-column>
        <el-table-column prop="c_option" label="选项C" width="100"></el-table-column>
        <el-table-column prop="d_option" label="选项D" width="100"></el-table-column>
        <el-table-column prop="right_ans" label="正确答案" width="150"></el-table-column>
        <el-table-column prop="max_score" label="分值" width="100"></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-checkbox v-model="row.selected">选中</el-checkbox>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="importQuestions" :disabled="!selectedQuestions.length">添加选中的题目</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  setup() {
    const tech_id = 1;
    const papers = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(5);
    const newPaperDialogVisible = ref(false);
    const importDialogVisible = ref(false);
    const selectedViewPaper = ref('all');
    const selectedImportPaper = ref(null);
    const newPaper = ref({ paper_title: '', max_score: 100 });
    const searchQuery = ref('');
    const questionBank = ref([]);
    const filteredQuestionBank = ref([]);
    const selectedQuestions = computed(() => filteredQuestionBank.value.filter(question => question.selected));

    const totalPapers = computed(() => (selectedViewPaper.value === 'all' ? papers.value.length : 1));

    const filteredTableData = computed(() => {
      if (selectedViewPaper.value === 'all') {
        return papers.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
      } else {
        return [papers.value[selectedViewPaper.value]];
      }
    });

    onMounted(() => {
      fetchPapers();
      fetchQuestionBank();
    });

    async function fetchPapers() {
      try {
        const response = await axios.get('http://8.138.12.59:1999/paperStore/getPaperStore?tech_id=1');
        if (response.data.status === 1) {
          papers.value = response.data.data.map(paper => {
            paper.questions = paper.questions || [];
            paper.max_score = calculateTotalScore(paper.questions);
            return paper;
          });
        } else {
          ElMessage.error('获取试卷失败');
        }
      } catch (error) {
        console.error('Failed to fetch papers:', error);
        ElMessage.error('获取试卷失败');
      }
    }

    function calculateTotalScore(questions) {
      if (!questions) return 0;
      return questions.reduce((sum, question) => sum + (question.max_score || 0), 0);
    }

    async function addNewPaper() {
      if (newPaper.value.paper_title.trim()) {
        const data = {
          tech_id: tech_id,
          paper_title: newPaper.value.paper_title,
          max_score:newPaper.value.max_score
        };
        try {

          const response = await axios.post('http://8.138.12.59:1999/paperStore/setPaperStore', data);

          if (response.data.status === 1) {
            papers.value.push({
              paper_id: response.data.paper_id,
              paper_title: newPaper.value.paper_title,
              max_score: newPaper.value.max_score,
              questions: []
            });
            newPaperDialogVisible.value = false;
            newPaper.value = { paper_title: '', max_score: 100 };
            handleCurrentChange(currentPage.value);
            ElMessage.success('试卷添加成功');
          } else {
            ElMessage.error('添加试卷失败');
          }
        } catch (error) {
          console.error('Failed to add new paper:', error);
          ElMessage.error('添加试卷失败');
        }
      } else {
        ElMessage.error('请填写试卷名称');
      }
    }

    async function deletePaper(index) {
      const paper = papers.value[index];
      try {
        const response = await axios.delete('http://8.138.12.59:1999/paperStore/deletePaperStore', {

          params: { paper_id: paper.paper_id }

        });
        if (response.data.status === 1) {
          papers.value.splice(index, 1);
          handleCurrentChange(currentPage.value);
          ElMessage.success('试卷删除成功');
        } else {
          ElMessage.error('删除试卷失败');
        }
      } catch (error) {
        console.error('Failed to delete paper:', error);
        ElMessage.error('删除试卷失败');
      }
    }

    function handleCurrentChange(page) {
      currentPage.value = page;
    }

    function openAddPaperDialog() {
      newPaperDialogVisible.value = true;
    }

    function openImportFromBankDialog() {
      importDialogVisible.value = true;
    }

    async function fetchQuestionBank() {
      try {
        const response = await axios.get('http://8.138.12.59:1999/QSSelect/getQSSelect?tech_id=1');
        if (response.data.status === 1) {
          questionBank.value = response.data.data.map(question => ({
            ...question,
            selected: false
          }));
          filteredQuestionBank.value = [...questionBank.value];
        } else {
          ElMessage.error('获取题库失败');
        }
      } catch (error) {
        console.error('Failed to fetch question bank:', error);
        ElMessage.error('获取题库失败');
      }
    }

    function filterQuestionBank() {
      const query = searchQuery.value.trim().toLowerCase();
      if (query) {
        filteredQuestionBank.value = questionBank.value.filter(question =>
          question.title && question.title.toLowerCase().includes(query)
        );
      } else {
        filteredQuestionBank.value = [...questionBank.value];
      }
    }


    async function addQs(paperid, qsList) {
      try {
        const response = await axios.post(`http://8.138.12.59:1999/paperStore/AddSeltoPaper?paper_id=${paperid}`, qsList);
        if (response.data.status === 0) {
          ElMessage.error('添加失败');
        }
      } catch (error) {
        console.error('Failed to fetch question bank:', error);
        ElMessage.error('连接失败');
      }
    }

    async function importQuestions() {
      const selectedPaper = papers.value[selectedImportPaper.value];
      const selectedQuestions = filteredQuestionBank.value.filter(question => question.selected);
      const qsList = selectedQuestions.map(qs => qs.qs_id);

      if (!selectedPaper) {
        ElMessage.warning('请选择试卷');
        return;
      }
      if (selectedQuestions.length === 0) {
        ElMessage.warning('请选择要导入的题目');
        return;
      }

      await addQs(selectedPaper.paper_id, qsList);
      selectedPaper.questions.push(...selectedQuestions);
      selectedPaper.max_score = calculateTotalScore(selectedPaper.questions);
      importDialogVisible.value = false;
      ElMessage.success('题目导入成功');
    }

    // 删除题目的方法
    function deleteQuestion(paper, questionIndex) {
      // 从指定的试卷中移除题目
      paper.questions.splice(questionIndex, 1);
      // 重新计算试卷的总分
      paper.max_score = calculateTotalScore(paper.questions);
      ElMessage.success('题目删除成功');
    }

    return {
      papers,
      currentPage,
      pageSize,
      newPaperDialogVisible,
      importDialogVisible,
      selectedViewPaper,
      selectedImportPaper,
      newPaper,
      searchQuery,
      filteredQuestionBank,
      selectedQuestions,
      totalPapers,
      filteredTableData,
      fetchPapers,
      addNewPaper,
      deletePaper,
      handleCurrentChange,
      openAddPaperDialog,
      openImportFromBankDialog,
      fetchQuestionBank,
      filterQuestionBank,
      importQuestions,
      calculateTotalScore,
      deleteQuestion
    };
  },
};
</script>

<style scoped>
.edit-paper {
  padding: 20px;
}

.top-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.full-width {
  width: 100%;
}

.paper-table .question-item {
  display: flex;
  justify-content: space-between;
}

.paper-table .question-header {
  display: flex;
  align-items: center;
}

.paper-table .question-index {
  font-weight: bold;
  margin-right: 8px;
}

.paper-table .question-title {
  flex-grow: 1;
}

.paper-table .question-type {
  margin-left: 20px;
  font-weight: bold;
}

.paper-table .question-options {
  padding-left: 20px;
  margin-bottom: 10px;
}

.correct-answer {
  padding-left: 20px;
  font-weight: bold;
  margin-top: 10px;
}

.delete-question-btn {
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-dialog {
  max-width: 600px;
}

.import-top {
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
}

.import-paper-select {
  margin-bottom: 20px;
}

.import-search {
  width: 300px;
}

/* 设置题库表格表头字体大小和加粗 */
.question-table >>> .el-table__header th {
  font-size: 16px;
  font-weight: bold;
}
</style>

